Page({
  data: {
    searchValue: '',
    showHistory: true,
    searchHistory: ['校园新闻', '活动通知', '学术讲座'],
    searchResult: [
      {
        id: 1,
        title: '校园新闻标题1',
        content: '这里是新闻的简要描述内容...',
        time: '2023-05-15'
      },
      {
        id: 2,
        title: '校园新闻标题2',
        content: '这里是新闻的简要描述内容...',
        time: '2023-05-10'
      }
    ]
  },

  onLoad() {
    // 从缓存加载搜索历史
    this.loadSearchHistory();
  },

  loadSearchHistory() {
    const history = wx.getStorageSync('searchHistory') || [];
    this.setData({
      searchHistory: history
    });
  },

  onSearch(e) {
    const keyword = e.detail;
    if (!keyword.trim()) return;
    
    this.setData({
      searchValue: keyword,
      showHistory: false
    });

    // 模拟搜索请求
    this.searchRequest(keyword);
    
    // 保存搜索历史
    this.saveSearchHistory(keyword);
  },

  onChange(e) {
    this.setData({
      searchValue: e.detail,
      showHistory: e.detail === ''
    });
  },

  searchRequest(keyword) {
    // 这里应该是实际的API请求
    console.log('搜索关键词:', keyword);
    // 模拟API返回
    setTimeout(() => {
      this.setData({
        searchResult: this.getMockResult(keyword)
      });
    }, 500);
  },

  getMockResult(keyword) {
    // 模拟搜索结果
    return [
      {
        id: Math.random(),
        title: `搜索结果1 - ${keyword}`,
        content: `这是关于${keyword}的搜索结果描述...`,
        time: '2023-05-18'
      },
      {
        id: Math.random(),
        title: `搜索结果2 - ${keyword}`,
        content: `这是关于${keyword}的另一个结果描述...`,
        time: '2023-05-17'
      }
    ];
  },

  saveSearchHistory(keyword) {
    let history = this.data.searchHistory;
    // 去重
    history = history.filter(item => item !== keyword);
    history.unshift(keyword);
    // 限制数量
    history = history.slice(0, 10);
    
    this.setData({
      searchHistory: history
    });
    
    wx.setStorageSync('searchHistory', history);
  },

  searchByHistory(e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({
      searchValue: keyword,
      showHistory: false
    });
    this.searchRequest(keyword);
  },

  clearHistory() {
    wx.showModal({
      title: '提示',
      content: '确定要清空搜索历史吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            searchHistory: []
          });
          wx.setStorageSync('searchHistory', []);
        }
      }
    });
  },

  navigateToDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/news/detail/detail?id=${id}`
    });
  }
});
